package com.hw.dagl.controller;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hw.dagl.model.DriverView;
import com.hw.dagl.model.Ftp;
import com.hw.dagl.model.Sys_User;
import com.hw.dagl.model.Vehicle;
import com.hw.dagl.service.ImageItemService;
import com.hw.dagl.service.impl.ImageItemServiceImpl;
import com.hw.dagl.service.impl.YxxxglServiceImpl;
import com.hw.dao.utils.ControllerUtil;
import com.hw.utils.FtpUtil;
import com.hw.utils.StringUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import nl.justobjects.pushlet.util.Log;
import sun.misc.BASE64Decoder;

@Controller
public class ImageItemController extends BaseController{
	private Logger logger=LoggerFactory.getLogger(YxxxglServiceImpl.class);
	
	@Autowired 
	private ImageItemServiceImpl imageItemService;
	

	@RequestMapping(method=RequestMethod.POST)
	public void UploadImageFtp(HttpServletRequest request,HttpServletResponse response,String imageBase64,String imageBase64Shot,Vehicle vehicle){
		boolean res=false;
		Sys_User user=(Sys_User) request.getSession().getAttribute("user");
		vehicle.setCjr(user.getYhdh().trim());
		String fileNameArea=request.getParameter("fileNameArea");
		String fileTypeArea=request.getParameter("fileTypeArea");
		String fileSerialNumber=request.getParameter("fileSerialNumber");
		String[] imageBase64str = imageBase64.split(",");
		String[] imageBase64Shotstr = imageBase64Shot.split(",");
		String[] fileTypeAreaStr = fileTypeArea.split(",");
		String[] fileNameAreaStr = fileNameArea.split(",");
		String[] fileSerialNumberStr = fileSerialNumber.split(",");
		String vehicleLsh=vehicle.getLsh();
		String lshStr;

		if(StringUtils.isEmpty(vehicleLsh)){
			 vehicleLsh="local_"+GetRandomNum1(10);
			 vehicle.setLsh(vehicleLsh);
		}
		/*if(StringUtils.isNotEmpty(vehicleLsh)){
			 String lshStrTemp = "流水号:"+vehicleLsh;
	         lshStr=lshStrTemp.substring(0, 8)+"*****"+lshStrTemp.substring(13);
		}else{
			vehicleLsh=GetRandomNum1(15);
			String lshStrTemp = "流水号:"+vehicleLsh;
	        lshStr=lshStrTemp.substring(0, 8)+"*****"+lshStrTemp.substring(13);
		}*/
		 Calendar now = Calendar.getInstance();
		 String TimeStrDir="/vehicle/"+now.get(Calendar.YEAR)+String.format("%0"+2+"d", now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/"+vehicleLsh+"/";
		Ftp ftp= FtpUtil.ftpConfig();
		FTPClient fc = null;
		try{
		fc=FtpUtil.ftpConnection(fc,ftp.getIpAddr(), ftp.getPort(), ftp.getDestpath(), ftp.getUserName(), ftp.getPwd());
		FtpUtil.changeWorkingDirectory(fc,TimeStrDir);
		}catch(Exception e){
			e.printStackTrace();
			ControllerUtil.renderJson(response, res, "encoding:UTF-8","no-cache:false");			
			return;
		}
		String [] ipAddr= new String[1024];
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(new Date());
		
		for(int k=0;k<imageBase64str.length;k++){
			if(imageBase64str[k].indexOf("http://")!=-1){
				ipAddr[k]=imageBase64str[k];
			}else{
			try {				
				/*if(StringUtils.isNotEmpty(fileSerialNumberStr[k])){
					  lshStr= "序列号:"+fileSerialNumberStr[k].substring(0, 5)+"****"+fileSerialNumberStr[k].substring(5);
				}else{
					  lshStr= "序列号:";
				}*/
		        //大图水印
		       // InputStream ins=SetWaterMark(imageBase64str[k], lshStr,100,40,time);
		        //缩略图水印
		       // InputStream inShot=SetWaterMark(imageBase64Shotstr[k], lshStr,20,8,time);
				InputStream ins =base64ToIo(imageBase64str[k]);
				InputStream inShot =base64ToIo(imageBase64Shotstr[k]);
				boolean flag= fc.storeFile(fileNameAreaStr[k], ins);
				boolean flagShot= fc.storeFile(fileNameAreaStr[k].replace(".jpg", ".thm.jpg"), inShot);
				if(flag&&flagShot){
					ipAddr[k]=ftp.getHttpAddr()+TimeStrDir+fileNameAreaStr[k];
				}
			   } catch (IOException e) {
				 Log.error(e.getMessage(), e);
				ControllerUtil.renderJson(response, res, "encoding:UTF-8","no-cache:false");
			}
		  }
	  }
		//断开ftp
		FtpUtil.closeFtp(fc);
		res=true;
		
		//根据生成的IP地址，拼装xml
		//创建文档并设置文档的根元素节点 
		 Element root = DocumentHelper.createElement("daglxx"); 
         Document document = DocumentHelper.createDocument(root);
        // 添加子节点:add之后就返回这个元素  
        for(int i=0;i<imageBase64str.length;i++){
	         Element element1 = root.addElement("address");
	         element1.addAttribute("id",fileTypeAreaStr[i]);
	         element1.setText(ipAddr[i]); 
        }
		String xmlStr= document.asXML();
		vehicle.setTpurl(xmlStr);
		//查询是否有记录
		boolean IsRecord = imageItemService.queryVehicleRecordAndPic(vehicle);
		boolean flag =false; //更新或插入成功与否标识
		imageItemService.setBean(vehicle);
		vehicle.setSerialNumber(fileSerialNumberStr[0]);
		if(IsRecord){
		     flag = imageItemService.updateVehicleRecordAndPic(vehicle);
		}else{
			 flag = imageItemService.insertVehicleRecordAndPic(vehicle,user);
		}
		ControllerUtil.renderJson(response, res&&flag, "encoding:UTF-8","no-cache:false");
	}
	
	public InputStream SetWaterMark(String imageBase64str,String WaterText,int font,int font2,String DateStr){
		BASE64Decoder decoder=new BASE64Decoder();
		byte[] bytes=null;
		ByteArrayOutputStream os = null;
		InputStream ins=null;
        ImageOutputStream imageOutput;
		try {
		bytes=decoder.decodeBuffer(imageBase64str);
		InputStream in = new ByteArrayInputStream(bytes);
		//BufferedImage img = ImageIO.read(in);
		BufferedImage img = ImageIO.read(in);
		int width = img.getWidth();
		int hight = img.getHeight();
		Graphics2D g2d = img.createGraphics();
		//g2d.setColor(Color.lightGray);
        //g2d.fillRect(0, 0, 1500, 700);
		
        Font f = new Font("宋体", Font.BOLD, font);
        Font f2 = new Font("宋体", Font.BOLD, font2);
        //Color[] colors = {Color.GRAY, Color.WHITE};
        g2d.setFont(f);

        //   平移原点到图形环境的中心
        g2d.translate(width / 7, hight / 7);
        float alpha = 0.4f; // 透明度   
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha)); 
        //   旋转文本
        for (int i = 0; i < 1; i++) {
            g2d.rotate(30 * Math.PI / 90);
            g2d.setPaint(Color.GRAY);
            g2d.drawString(WaterText, 40, 0);
        }
        
        g2d.setFont(f2);
        g2d.rotate(30 * Math.PI /-90);
        g2d.translate(-width / 7, -width / 7);
        g2d.drawString(DateStr,0,0);
        
        g2d.dispose();
        
        os = new ByteArrayOutputStream(); 		
		imageOutput = ImageIO.createImageOutputStream(os);
		ImageIO.write(img, "jpg",imageOutput);
	    ins = new ByteArrayInputStream(os.toByteArray());
		} catch (IOException e) {
			Log.error(e.getMessage(), e);
		}		                
        
        return ins;
        /*byte[] b = new byte[1024];  
        while(ins.read(b) != -1) {  
            out.write(b);  
        }
        ins.close();
        out.close();*/
        
        /*ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);  
        encoder.encode(img);  
        byte[] resultByte = jpegOutputStream.toByteArray(); 
        InputStream ins = new ByteArrayInputStream(resultByte);*/
	}
	public InputStream base64ToIo(String imageBase64str){
		BASE64Decoder decoder=new BASE64Decoder();
		byte[] bytes=null;
		InputStream ins=null;
		try {
		bytes=decoder.decodeBuffer(imageBase64str);
		ins = new ByteArrayInputStream(bytes);        
		} catch (IOException e) {
			Log.error(e.getMessage(),e);
		}		                
        
        return ins;
	}
	@RequestMapping(method=RequestMethod.POST)
	public void UploadDriverImageFtp(HttpServletRequest request,HttpServletResponse response,String imageBase64,DriverView driver){
		boolean res=false;
		Sys_User user=(Sys_User) request.getSession().getAttribute("user");
		driver.setCjr(user.getYhdh().trim());
		String fileNameArea=request.getParameter("fileNameArea");
		String fileTypeArea=request.getParameter("fileTypeArea");
		String[] imageBase64str = imageBase64.split(",");
		String[] fileTypeAreaStr = fileTypeArea.split(",");
		String[] fileNameAreaStr = fileNameArea.split(",");
		//String vehicleXh=request.getParameter("vehicleXh");
		String vehicleXh=driver.getXh();
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	    //String TimeStr = sdf.format(new Date());
		 Calendar now = Calendar.getInstance();
		 String TimeStrDir="/driver/"+now.get(Calendar.YEAR)+String.format("%0"+2+"d", now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/"+vehicleXh+"/";
		Ftp ftp= FtpUtil.ftpConfig();
		FTPClient fc = null;
		try{
		fc=FtpUtil.ftpConnection(fc,ftp.getIpAddr(), ftp.getPort(), ftp.getDestpath2(), ftp.getUserName(), ftp.getPwd());
		FtpUtil.changeWorkingDirectory(fc,TimeStrDir);
		}catch(Exception e){
			ControllerUtil.renderJson(response, res, "encoding:UTF-8","no-cache:false");
		}
		String [] ipAddr= new String[300];
		for(int k=0;k<imageBase64str.length;k++){
			if(imageBase64str[k].indexOf("http://")!=-1){
				ipAddr[k]=imageBase64str[k];
			}else{
			try {
				BASE64Decoder decoder=new BASE64Decoder();
				byte[] bytes=decoder.decodeBuffer(imageBase64str[k]);
				InputStream in = new ByteArrayInputStream(bytes);
				boolean flag= fc.storeFile(fileNameAreaStr[k], in);
				if(flag){
					ipAddr[k]=ftp.getHttpAddr()+TimeStrDir+fileNameAreaStr[k];
				}
			   } catch (IOException e) {
				ControllerUtil.renderJson(response, res, "encoding:UTF-8","no-cache:false");
				e.printStackTrace();
			}
		  }
	  }
		//断开ftp
		FtpUtil.closeFtp(fc);
		res=true;
		
		//根据生成的IP地址，拼装xml
		//创建文档并设置文档的根元素节点 
		 Element root = DocumentHelper.createElement("daglxx"); 
         Document document = DocumentHelper.createDocument(root);
        // 添加子节点:add之后就返回这个元素  
        for(int i=0;i<imageBase64str.length;i++){
	         Element element1 = root.addElement("address");
	         element1.addAttribute("id",fileTypeAreaStr[i]);
	         element1.setText(ipAddr[i]); 
        }
		String xmlStr= document.asXML();
		driver.setTpurl(xmlStr);
		//查询是否有记录
		boolean IsRecord = imageItemService.queryDriverRecordAndPic(driver);
		boolean flag =false; //更新或插入成功与否标识
		if(IsRecord){
		     flag = imageItemService.updateDriverRecordAndPic(driver);
		}else{
			 flag = imageItemService.insertDriverRecordAndPic(driver);
		}
		ControllerUtil.renderJson(response, res&&flag, "encoding:UTF-8","no-cache:false");
	}
	
	//生成缩略图
		public boolean sntPic(int width,int height,InputStream input){
			BufferedImage image=null;
			Image img=null;
			BufferedOutputStream out =null;
			try {
			    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				//out= new BufferedOutputStream(new FileOutputStream(new File(destFile)));
				 img=ImageIO.read(input);
				 image.getGraphics().drawImage(img, 0, 0, width, height, null);
				 JPEGImageEncoder encode= JPEGCodec.createJPEGEncoder(out);
				 encode.encode(image);
				 image.flush();
				 out.flush();
				 out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return true;
			
		}
	
	  //生成固定长度随机数
    public String GetRandomNum(int number){   	
	    char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',  
            'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',  
            'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',  
            'x', 'y', 'z'};
         String res = "";
         Random random = new Random();
         for(int i = 0; i < number ; i ++) {
        	 int id = random.nextInt(62);
             res += chars[id];
         }
         return res;
    }
    public String GetRandomNum1(int number){   	
	    char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
         String res = "";
         Random random = new Random();
         for(int i = 0; i < number ; i ++) {
        	 int id = random.nextInt(10);
             res += chars[id];
         }
         return res;
    }
}
